package HTTP

import (
	"SQL/FSDB"
	"net/http"
)

type friendInfo struct {
	FriendID string
	Nickname string
	Icon     string
}

func getFriendList(w http.ResponseWriter, req *http.Request) {

	var resCode = http.StatusOK
	var msg = ""
	var res interface{}
	defer func() {
		writeResult(w, resCode, msg, res)
	}()

	userID := req.FormValue("userID")
	pageIndex := req.FormValue("pageIndex")
	pageSize := req.FormValue("pageSize")

	ok := false
	if ok, resCode, msg = isArgsEmpty(userID, pageIndex, pageSize); ok {
		return
	}
	if ok, resCode, msg = isValidID(userID, "UserID"); !ok {
		return
	}
	pSize := 0
	if ok, pSize, resCode, msg = isValidPageSize(pageSize); !ok {
		return
	}
	pIndex := 0
	if ok, pIndex, resCode, msg = isValidPageIndex(pageIndex); !ok {
		return
	}

	errCode, errMsg, friendList := getFriendListFromDB(userID, pIndex, pSize)
	msg = errMsg
	if errCode != Success {
		resCode = errCode
		return
	}
	res = friendList
}

func getFriendListFromDB(userID string, pageIndex int, pageSize int) (errCode int, errMsg string, friendList interface{}) {

	friendListSQL := `SELECT id,nickname,icon 
						FROM objects 
						WHERE isuser='true' AND id <> $1  
						LIMIT $2 
						OFFSET $3;`

	rows, err := FSDB.Query(friendListSQL, userID, pageSize, pageIndex)
	defer rows.Close()
	if err != nil {
		return errDBExecFailed, err.Error(), nil
	}
	friendRows := make([]friendInfo, 0)
	for rows.Next() {
		var (
			id       string
			icon     string
			nickname string
		)
		err := rows.Scan(&id, &icon, &nickname)
		if err != nil {
			return errDBExecFailed, err.Error(), nil
		}
		info := friendInfo{id, icon, nickname}
		friendRows = append(friendRows, info)
	}
	return Success, "获取好友列表成功！", friendRows
}
